package app

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"github.com/bwmarrin/snowflake"
	"github.com/gin-gonic/gin"
	"github.com/skip2/go-qrcode"
	"golang.org/x/crypto/bcrypt"
	"image/color"
	"image/jpeg"
	"math/rand"
	"net/http"
	"strconv"
	"time"
)

func Success(ctx *gin.Context, data interface{}) {
	ctx.JSON(
		http.StatusOK,
		gin.H{
			"code": 0,
			"msg":  "OK",
			"data": data,
		},
	)
}

func HashAndSalt(pwd []byte) string {
	hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
	if err != nil {

	}
	return string(hash)
}

func ValidatePasswords(hashedPwd string, plainPwd []byte) bool {
	byteHash := []byte(hashedPwd)
	err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
	if err != nil {
		return false
	}
	return true
}

func GenerateID() (int64, error) {
	node, err := snowflake.NewNode(1)
	if err != nil {
		fmt.Println(err)
		return 0, err
	}

	// Generate a snowflake ID.
	id := node.Generate()
	return int64(id), nil
}

func GenerateTakeCode() string {
	rand.Seed(time.Now().Unix())
	res := rand.Intn(989999) + 10000
	ans := ""
	for i := 0; i < 8; i++ {
		code := strconv.Itoa(res % 10)
		res /= 10
		ans += code
	}
	return ans
}

/*
CreatePNG
@Desc	生成二维码
@Param	content 	string	二维码内容
@Param	fileSize 	int		二维码大小
@Param	fileName 	string	文件昵称
*/
func CreatePNG(content string, fileSize int) (s string, err error) {
	//生成一个二维码对象
	q, err := qrcode.New(content, qrcode.Medium)
	if err != nil {
		return "", err
	}

	//q.DisableBorder = true          //去除边框
	q.BackgroundColor = color.White //二维码背景颜色
	q.ForegroundColor = color.Black //二维码条纹颜色
	img := q.Image(fileSize)

	emptyBuff := bytes.NewBuffer(nil)                  //开辟一个新的空buff
	jpeg.Encode(emptyBuff, img, nil)                   //img写入到buff
	dist := make([]byte, 50000)                        //开辟存储空间
	base64.StdEncoding.Encode(dist, emptyBuff.Bytes()) //buff转成base64
	index := bytes.IndexByte(dist, 0)                  //这里要注意，因为申请的固定长度数组，所以没有被填充完的部分需要去掉，负责输出可能出错
	baseImage := dist[0:index]
	return string(baseImage), nil

}
